<?php

class Photos extends Controller {

    function upload() {
        if (!$this->session->get("authenticated")) {
            $this->redirect("/users/login");
        }

        if (isset($_FILES["file"])) {
            if ($_FILES["file"]["error"] > 0) {
                /* Error */
            } else {
                $file_tmp_name = $_FILES["file"]["tmp_name"];
                $file_name = $_FILES["file"]["name"];

                $file_info = pathinfo($file_name);
                $file_extension = $file_info['extension'];
                $random_name = md5(uniqid(rand(), true));

                $file_name = $random_name . "." . $file_extension;
                $file_path = ROOT . DS . "public" . DS . "photos" . DS;

                move_uploaded_file($file_tmp_name, $file_path . $file_name);

                if ($file_extension == "jpg" || $file_extension == "jpeg") {
                    $img = imagecreatefromjpeg($file_path . $file_name);
                } else if ($file_extension == "png") {
                    $img = imagecreatefrompng($file_path . $file_name);
                } else if ($file_extension == "bmp") {
                    $img = imagecreatefromwbmp($file_path . $file_name);
                }
                
                $width = imagesx($img);
                $height = imagesy($img);

                $new_width = 200;
                $new_height = floor($height * (200 / $width));
                $tmp_img = imagecreatetruecolor($new_width, $new_height);

                imagecopyresized($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
                imagejpeg($tmp_img, $file_path . "thumbs" . DS . $file_name, 100);

                $photo = array(
                    "author_user_id" => $this->session->get("user_id"),
                    "title" => $_POST["title"],
                    "category" => $_POST["category"],
                    "keywords" => $_POST["keywords"],
                    "description" => $_POST["description"],
                    "date_taken" => $_POST["date_taken"],
                    "filename" => $file_name,
                    "access_rule" => $_POST["access_rule"],
                    "comment_rule" => $_POST["comment_rule"]
                );

                $this->Photo->add($photo);
                $last_insert_id = $this->Photo->insert_id();

                if ($this->session->get("twitter_username") !== '') {
                    $photo_link = BASE_PATH . "/photos/view/$last_insert_id";
                    $shortened_photo_link = $this->bitly->get_bitly_short_url($photo_link);

                    $this->twitter->statusesUpdate("Saya baru saja mengunggah foto baru di Bekti Photo Sharing. Lihat foto saya di $shortened_photo_link.");
                }

                $this->session->set_flash("Your photo has been uploaded successfully.");

                $this->_auto_render = false;
                $this->redirect("/photos/view/$last_insert_id");
            }
        }

        $this->set('title', 'Upload Photo');
    }

    function view($id) {
        $User = new User();
        $photo = $this->Photo->get($id);

        $access_rule = $photo["Photo"]["access_rule"];
        $author_user_id = $photo["Photo"]["author_user_id"];

        if ($access_rule == 4) {
            if ($author_user_id != $this->session->get("user_id")) {
                $this->_auto_render = false;
            }
        } else if ($access_rule == 3) {
            if (!(($this->session->get("authenticated")) && ($User->follows($this->session->get("user_id"), $author_user_id)))) {
                $this->_auto_render = false;
            }
        } else if ($access_rule == 2) {
            if (!$this->session->get("authenticated")) {
                $this->_auto_render = false;
            }
        }

        if (($author_user_id == $this->session->get("user_id")) || ($this->session->get("role_id") == 1)) {
            $this->_auto_render = true;
        }
        
        $tags = $this->Photo->tag($id);

        $this->set("title", "View Photo Details");
        $this->set("photo", $photo);
        $this->set("tags", $tags);
    }

    function get_comments($id, $page) {
        $offset = ((int)$page - 1) * 5;
        $photo = $this->Photo->get_comments($id, $offset);

        $this->_render_header = false;
        $this->set("photo_id", $id);
        $this->set("comments", $photo);
    }

    function comment($method, $id, $comment_id = NULL) {
        if (!$this->session->get("authenticated")) {
            $this->_auto_render = false;
            $this->session->set_flash("You must login first to perform that action.");
            $this->redirect("/users/login");
            return;
        }

        if ($method == "add") {
            $comment["post_id"] = $id;
            $comment["author_user_id"] = $_POST["author_user_id"];
            $comment["content"] = $_POST["photo_comment"];

            $this->Photo->add_comment($comment);
            $this->session->set_flash("Your comment has been added.");
            $this->_auto_render = false;
        } else if ($method == "delete") {
            $this->Photo->delete_comment($comment_id);
            $this->session->set_flash("Comment has been deleted.");
            $this->_auto_render = false;
        }

        $this->redirect("/photos/view/$id");
    }

    function rate($method, $id) {
        if (!$this->session->get("authenticated")) {
            $this->_auto_render = false;
            $this->session->set_flash("You must login first to perform that action.");
            $this->redirect("/users/login");
            return;
        }

        $this->Photo->rate($method, $id);

        $this->session->set_flash("Your rating has been saved.");
        $this->_auto_render = false;
        $this->redirect("/photos/view/$id");
    }

    function edit($id) {
        if (!$this->session->get("authenticated")) {
            $this->_auto_render = false;
            $this->session->set_flash("You must login first to perform that action.");
            $this->redirect("/users/login");
            return;
        }

        if (isset($_POST["submit"])) {
            $photo = array(
                "id" => $id,
                "category" => $_POST["category"],
                "title" => $_POST["title"],
                "keywords" => $_POST["keywords"],
                "description" => $_POST["description"],
                "date_taken" => $_POST["date_taken"],
                "access_rule" => $_POST["access_rule"],
                "comment_rule" => $_POST["comment_rule"],
                "tags" => $_POST["tag"]
            );
            
            $user = $this->session->get("user_id");

            $this->Photo->add_notification($user, $photo);
            $this->Photo->update($photo);
            $this->session->set_flash("Your photo information has been updated successfully.");
            $this->_auto_render = false;
            $this->redirect("/photos/view/$id");
        }
        $this->set("title", "Edit Photo Information");
        $this->set("photo", $this->Photo->select($id));
        $this->set("tags", $this->Photo->tag($id));
    }

    function delete($user_id, $photo_id) {
        if (!$this->session->get("authenticated")) {
            $this->_auto_render = false;
            $this->session->set_flash("You must login first to perform that action.");
            $this->redirect("/users/login");
            return;
        }

        $user = $this->Photo->user_photos($user_id);
        if ($user['User']['photo_id'] == $photo_id) {
            $this->Photo->restore_photo($user_id);
        }

        $this->Photo->delete($photo_id);

        $this->session->set_flash("Your photo has been deleted successfully.");
        $this->_auto_render = false;
        $this->redirect("/users/view/$user_id");
    }

    function feed() {
        $this->set("title", "Home");
    }

    function feed_ajax($orderby = "newest", $page = "1") {
        $User = new User();

        $offset = ((int)$page - 1) * 21;

        if ($orderby == "newest") {
            $photos = $this->Photo->select_newest($offset);
        } else if ($orderby == "popular") {
            $photos = $this->Photo->select_popular($offset);
        } else if ($orderby == "highest") {
            $photos = $this->Photo->select_highest($offset);
        }

        $count = count($photos);

        for ($i = 0; $i < $count; $i++) {
            $access_rule = $photos[$i]["Photo"]["access_rule"];
            $author_user_id = $photos[$i]["Photo"]["author_user_id"];

            if ($access_rule == 4) {
                if (!($this->session->get("authenticated") && ($author_user_id == $this->session->get("user_id")))) {
                    unset($photos[$i]);
                }
            } else if ($access_rule == 3) {
                if (!$this->session->get("authenticated")) {
                    unset($photos[$i]);
                }

                if (!$User->follows($this->session->get("user_id"), $author_user_id) && ($author_user_id != $this->session->get("user_id"))) {
                    unset($photos[$i]);
                }
            } else if ($access_rule == 2) {
                if (!$this->session->get("authenticated")) {
                    unset($photos[$i]);
                }
            }
        }

        $photos = array_values($photos);

        $this->_render_header = false;
        $this->set("photos", $photos);
    }

    function add_tag() {
        if (!$this->session->get("authenticated")) {
            $this->_auto_render = false;
            $this->session->set_flash("You must login first to perform that action.");
            $this->redirect("/users/login");
            return;
        }
        $id = $_SESSION['user_id'];
        $users = $this->Photo->add_tag($id);
        $this->_render_header = false;
        $this->set("title","Select User");
        $this->set("users",$users);
    }
}
